package com.yjf.ljr.connection;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.NameValuePair;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.text.TextUtils;

import com.yjf.ljr.common.CommonData;
import com.yjf.ljr.common.Logger;
import com.yjf.ljr.model.ResponseObject;
import com.yjf.ljr.parser.BaseParser;
import com.yjf.ljr.parser.DataClass;

public class IjConnect {

	/**
	 *  Http Get 方式, XML解析
	 */
	public static ResponseObject doRequest(String urlStr, BaseParser parser) {
		String xmlStr = getRequestResult(urlStr);
		return parseResponse(parser, xmlStr);
	}

	/**
	 * Http Get 方式获取json数据并解析，要预先写好解析json的数据结构类dc
	 * 
	 * @param urlStr
	 *            请求的url
	 * @param dataClass
	 *            数据结构
	 * @return 解析后的结果
	 */
	public static <T extends DataClass> void doRequest(String urlStr, T dataClass) {
		String xmlStr = getRequestResult(urlStr);
		dataClass.getDataClassFromStr(xmlStr);
	}
	
	/**
	 * 网络请求，Get方式
	 * @param urlStr
	 * @return
	 */
	public static String getRequestResult(String urlStr){
		Logger.i("请求: " + urlStr);
		HttpURLConnection hc = null;
		String xmlStr = "";

		try {
			URL url = new URL(urlStr);
			hc = (HttpURLConnection) url.openConnection();
			
//			if (urlStr.indexOf("?") > 0) {
//				String sign = urlStr.substring(urlStr.indexOf("?") + 1);
//				try {
//					sign = URLDecoder.decode(sign, "utf-8");
//				} catch (UnsupportedEncodingException e) {
//					e.printStackTrace();
//				}
//				String signMD5 = Base64.encode(HMacMD5.getHmacMd5Byte(CommonData.MD5KEY, sign));
//				hc.addRequestProperty("sign", signMD5);
//				hc.addRequestProperty("machinekey", SplashActivity.mMachineKey);
//			}
			
			hc.setDoInput(true);
			hc.setDoOutput(true);
			hc.setReadTimeout(30000);
			hc.setConnectTimeout(15000);
			hc.setChunkedStreamingMode(0);
			hc.addRequestProperty("Cookie", CommonData.SESSIONID);
			getRequestHeader(hc);	// 获取http返回的头信息
			InputStream is = hc.getInputStream();
			xmlStr = InputStreamToString(is);
		} catch (Exception e) {
			e.printStackTrace();
		}
		Logger.i("返回: " + xmlStr);
		return TextUtils.isEmpty(xmlStr) ? "" : xmlStr;
	}

	/**
	 *  Http Post 方式
	 *  
	 *  最常用的Http请求无非是get和post，get请求可以获取静态页面，也可以把参数放在URL字串后面，
	 *  传递给servlet，post与get的不同之处在于post的参数不是放在URL字串里面，而是放在http请求的正文内。
	 *	在Java中可以使用HttpURLConnection发起这两种请求
	 */
	public static ResponseObject doRequest(String urlStr, BaseParser parser, List<NameValuePair> params) {
		HttpURLConnection hc = null;
		URL url;
		ResponseObject respObj = null;
		String xmlStr = "";
		Logger.i("请求: " + urlStr);

		try {
			url = new URL(urlStr);
			hc = (HttpURLConnection) url.openConnection();
			
	        hc.setRequestMethod("POST");// Set the post method. Default is GET
	        hc.setUseCaches(false);// Post 请求不能使用缓存
	        hc.setInstanceFollowRedirects(true);
			hc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

			hc.setDoInput(true);
			hc.setDoOutput(true);
			hc.setReadTimeout(15000);
			hc.setConnectTimeout(15000);
			DataOutputStream out = new DataOutputStream(hc.getOutputStream());
			
	        // The URL-encoded contend
			// Post 传参方式：param = "CorpID=123&LoginName=qqq&name=" + URLEncoder.encode("汉字","GBK"); 
	        String content = "";
	        if (params != null && params.size() > 0) {
				for (NameValuePair nameValuePair : params) {
					content += nameValuePair.getName() + "=" + nameValuePair.getValue() + "&";
				}
				if (content.length() > 0) {
					content = content.substring(0, content.length() - 1);
				}
			}
	        out.writeBytes(content); 
	        out.flush();
	        out.close(); // flush and close

			InputStream is = hc.getInputStream();
			xmlStr = InputStreamToString(is);
		} catch (Exception e) {
			e.printStackTrace();
		}

		Logger.i("返回: " + xmlStr);
		respObj = parseResponse(parser, xmlStr);
		return respObj;
	}

	/**
	 * 解析XML字符串
	 */
	public static ResponseObject parseResponse(BaseParser parser, String xmlStr) {
		ResponseObject respObj;
		InputStream in;
		if(!TextUtils.isEmpty(xmlStr)) {
			try {
				in = new ByteArrayInputStream(xmlStr.getBytes("utf-8"));
				SAXParserFactory spf = SAXParserFactory.newInstance();
				SAXParser sp = spf.newSAXParser();
				XMLReader xr = sp.getXMLReader();
				xr.setContentHandler(parser);
				xr.parse(new InputSource(in));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		respObj = parser.getRespObject();
		respObj.data = xmlStr;
		return respObj;
	}
	
	public static void getRequestHeader(HttpURLConnection hc) {
		Map<String, List<String>> map = hc.getHeaderFields();
		List<String> cookieList = null;
		if (map != null && map.size() > 0) {
			cookieList = map.get("Set-Cookie");
			if (cookieList != null && cookieList.size() > 0) {
				String coolieTmp = cookieList.toString();
				if (coolieTmp.indexOf("ERDSESSIONID=") != -1) {
					CommonData.SESSIONID = coolieTmp;
				}
//				String[] cookies = cookieList.get(0).split(";");
//				for (int i = 0; i < cookies.length; i++) {
//					if (cookies[i].indexOf("ERDSESSIONID=") != -1) {
//						CommonData.SESSIONID = cookies[i];
//						break;
//					}
//				}
			}
		}
	}

	public static String InputStreamToString(InputStream is) {
		StringBuilder sb = new StringBuilder();
		String readline = "";
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
			while ((readline = br.readLine()) != null) {
				sb.append(readline).append("\n");
			}
			br.close();
		} catch (IOException ie) {
			System.out.println("converts failed.");
		}
		return sb.toString();
	}
	
}